App({

  onLaunch: function () {
    if (wx.getStorageSync('login_time') == "") {
      wx.setStorageSync("login_time", 1400000000);
    }
    // var time = new Date(new Date(new Date().toLocaleDateString()).getTime())/1000;
    // if (wx.getStorageSync('login_time') < time) {
    //   wx.setStorageSync("login_time", time);
    //   wx.showModal({
    //     title: '提醒',
    //     content: '当前绑定车型：'+wx.getStorageSync('carType')+'\r 当前绑定车号：'+wx.getStorageSync('carNo')+'\r 是否修改绑定?',
    //     success: function(res) {
    //       if (res.confirm) {
    //         wx.navigateTo({
    //           url: '/pages/mine/changecar'
    //         })
    //       }
    //     }
    //   })
    // }
  },
  onShow: function (e) {
    if (e.shareTicket) {
      console.log(e.shareTicket);
    }
    this.getToken();
    setTimeout(function () {
      getApp().checknewmsg();
    }, 5000);
    setTimeout(function () {
      getApp().getLocation();
    }, 5000);
  },
  checkLogin: function () {
    var user_id = wx.getStorageSync('user_id');

    if (user_id == undefined || user_id == null || user_id == "") {
      wx.showModal({
        title: '提示',
        content: '您需要先登录！',
        showCancel: false,
        success: function (res) {
          wx.navigateTo({
            url: '/pages/login/login'
          })
        }
      })
    }
  },
  onHide: function () {

  },

  addListenerchatlist: function (chatlistcallback) {
    this.chatlistcallback = chatlistcallback;
  },
  addListenerindex: function (indexcallback) {
    this.indexcallback = indexcallback;
  },
  addListenerchat: function (chatcallback) {
    this.chatcallback = chatcallback;
  },
  setChangedData: function (data) {
    if(data === null || data === ''){
      return false;
    }
    this.data = data;
    if (this.indexcallback != null) {
      this.indexcallback(data);
    }
    // if (this.chatlistcallback != null) {
    //   this.chatlistcallback(data);
    // }
    if (this.chatcallback != null) {
      this.chatcallback(data);
    }
  },
  alert: function (content) {
    wx.showModal({
      title: '提示',
      content: content
    })

  },
  toast: function (content) {
    wx.showToast({
      title: content,
      mask: true,
      icon: 'success',
      duration: 1000
    })
  },
  sp: function (content = "加载中") {
    wx.showLoading({
      title: content,
      mask: true
    })
  },
  hp: function () {
    wx.hideLoading();
  },
  checknewmsg: function () {
    console.log("checknewmsg");
    var that = this;
    var user_id = wx.getStorageSync('user_id');
    if (user_id != undefined && user_id != null && user_id != "") {
      wx.request({
        url: getApp().globalData.javaurl + '/common/chat/getNewMsg',
        method: 'POST',
        header: {
          "content-type": "application/x-www-form-urlencoded",
          "Authorization": wx.getStorageSync('token')
        },
        success: function (res) {
          if (res.header.Authorization != "" && res.header.Authorization != undefined) {
            wx.setStorageSync('token', res.header.Authorization);
          }
          if (res.header.authorization != "" && res.header.authorization != undefined) {
            wx.setStorageSync('token', res.header.authorization);
          }
          that.setChangedData(res.data.data);
          setTimeout(function () {
            getApp().checknewmsg();
          }, 5000);
        }
      });
    }else{
      setTimeout(function () {
        getApp().checknewmsg();
      }, 5000);
    }

  },
  getToken: function () {
    var that = this;
    wx.request({
      url: that.globalData.javaurl + '/login',
      method: 'POST',
      dataType: "json",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        "username": wx.getStorageSync('login_name'),
        "password": wx.getStorageSync('pwd')
      },
      success: function (res) {
        console.log(res.data);
        wx.setStorageSync('token', res.data.data.token);
      }
    });
  },
  /**
   * TODO(获取当前的地理位置)
   * @auther zhangQ
   * @date 2018/4/11 17:08
   */
  getLocation: function () {
    wx.getLocation({
      success: function (locationObj) {
        var param = {
          longitude: locationObj.longitude,
          latitude: locationObj.latitude,
          userId: wx.getStorageSync('user_id')
        }
        // {latitude, longitude, speed, accuracy, altitude, verticalAccuracy, horizontalAccuracy}
        //console.log(param);
        if (param.userId=="")
        {
          setTimeout(function () {
            getApp().getLocation()
          }, 1000 * 60 * 3)
          return;
        }
        getApp().request({
          url: '/sendDriverLocation',
          data: param,
          mask: false
        }).then((res) => {
          if (+res.data.isSuccess !== 1) {
            console.log('位置信息发送失败')
          }
          setTimeout(function () {
            getApp().getLocation()
          }, 1000 * 60 * 3)
        })
      },
      fail: function () {
        console.log('位置获取错误！')
      }
    })
  },
    /**
   * TODO(封装带Token的请求)
   * @param
   * @auther john
   * @date 2018/6/26 10:26
   **/
  requestPromise: function (url, params = {},header ={}, method = "GET") {
    if ("undefined" == typeof header['content-type'])
    {
      header['content-type'] = 'application/json';
    }
    let Authorization = wx.getStorageSync('token')
    if (Authorization) {
      header['Authorization'] = Authorization;
    }
    return new Promise(function (resolve, reject) {
      wx.request({
        url: url,
        data: params,
        method: method,
        header: header,
        success: function (res) {
          console.log("---------success--------" + url);
          if (res.statusCode != 200){
            getApp().alert("网络异常:");
          }
          resolve(res);
        },
        fail: function (err) {
          reject(err)
          console.log("---------failed---------" + url);
        }
      })
    });
  },
  /**
   * TODO(封装wx.request的promise请求)
   * @param :::
   * @return result:::
   * @auther zhangQ
   * @date 2018/4/11 18:29
   */
  request: function (param) {
    var config = Object.assign({
      mask: true
    }, param)
    if (!(param && param.url)) {
      return Promise.reject("参数错误")
    }
    let headerObj = param.header ? param.header : {}
    headerObj['content-type'] = 'application/x-www-form-urlencoded'
    let sendData = {}
    if (param.data) {
      sendData = param.data
    }
    let Authorization = wx.getStorageSync('token')
    if (Authorization) {
      headerObj.Authorization = Authorization
      sendData.Authorization = Authorization
    }
    // 转码
    // sendData = qs.stringify(sendData)
    return new Promise(function (resolve, reject) {
          config.mask && getApp().sp()
          wx.request({
            url: getApp().globalData.javaurl + param.url,
            method: param.method ? param.method : 'POST',
            dataType: param.dataType ? param.dataType : 'json',
            header: headerObj,
            data: sendData,
            success: function (res) {
              config.mask && getApp().hp()
              if (+res.data.isSuccess === 1) {
                resolve(res)
              } else {
                wx.showModal({
                  title: '提示',
                  content: res.data.res,
                  showCancel: false,
                  success: function (res) {
                    reject(res)
                    if (+res.data.isSuccess === 402) {
                      wx.clearStorageSync();
                      wx.navigateTo({
                        url: '/pages/login/login'
                      })
                    }
                  }
                })
              }
            },
            fail: function () {
              config.mask && getApp().hp()
              wx.showModal({
                title: '提示',
                content: '错误',
                showCancel: false,
                success: function (res) {
                  reject(res)
                }
              })
            },
            complete: function (res) {
              if (res.header.Authorization) {
                wx.setStorageSync('token', res.header.Authorization)
              }
              config.mask && getApp().hp()
            }
          })
        }
    )
  },
  globalData: {
    apiurl: 'https://tp.x-link.cc/DriverApi/',
    javaurl: 'https://www.x-link.cc',
    // javaurl: 'http://localhost:8080',
    // javaurl: 'http://192.168.1.103:8080',
    weidu: 0
  }
});